package com.simplehire.controller;

import com.simplehire.dto.ConversationRequest;
import com.simplehire.model.InterviewResult;
import com.simplehire.model.User;
import com.simplehire.service.AIService;
import com.simplehire.service.DeepSeekService;
import com.simplehire.service.DoubaoService;
import com.simplehire.service.TongyiService;
import com.simplehire.service.ResumeParserService;
import com.simplehire.service.UserService;
import com.simplehire.repository.InterviewResultRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/interview")
public class InterviewController {

    private static final Logger logger = LoggerFactory.getLogger(InterviewController.class);

    // 服务依赖
    private final ResumeParserService resumeParserService;
    private final DeepSeekService deepSeekService;
    private final DoubaoService doubaoService;
    private final TongyiService tongyiService;
    private final UserService userService;
    private final InterviewResultRepository interviewResultRepository;
    private final String defaultModel;
    private final List<String> availableModels;

    // 完整的构造函数依赖注入
    public InterviewController(ResumeParserService resumeParserService,
                               DeepSeekService deepSeekService,
                               DoubaoService doubaoService,
                               TongyiService tongyiService,
                               UserService userService,
                               InterviewResultRepository interviewResultRepository,
                               @Value("${ai.default.model:deepseek}") String defaultModel) {
        this.resumeParserService = resumeParserService;
        this.deepSeekService = deepSeekService;
        this.doubaoService = doubaoService;
        this.tongyiService = tongyiService;
        this.userService = userService;
        this.interviewResultRepository = interviewResultRepository;
        this.defaultModel = defaultModel;
        this.availableModels = List.of("deepseek", "doubao", "tongyi");
    }

    /**
     * 面试分析入口页面 - 显示模型选择、简历上传/输入区域
     */
    @GetMapping
    public String interviewPage(Model model) {
        // 传递可用模型列表和默认模型到前端
        model.addAttribute("models", availableModels);
        model.addAttribute("defaultModel", defaultModel);
        return "interview";
    }

    /**
     * 处理简历分析请求 - 接收模型选择参数，使用选定模型进行分析
     */
    @PostMapping("/analyze")
    public String analyzeResume(@RequestParam(value = "resumeFile", required = false) MultipartFile file,
                                @RequestParam(value = "resumeText", required = false) String resumeText,
                                @RequestParam(value = "model", defaultValue = "${ai.default.model}") String model,
                                Authentication authentication,
                                Model modelAttr) {
        logger.info("收到简历分析请求，选择的模型: {}", model);

        try {
            // 验证用户身份
            User user = userService.findByUsername(authentication.getName());
            if (user == null) {
                modelAttr.addAttribute("error", "用户身份验证失败");
                return "interview";
            }

            // 解析简历内容（文件或文本）
            String parsedText = parseResumeContent(file, resumeText);
            if (parsedText == null || parsedText.trim().isEmpty()) {
                modelAttr.addAttribute("error", "请上传简历文件或输入简历文本内容");
                modelAttr.addAttribute("models", availableModels);
                modelAttr.addAttribute("defaultModel", defaultModel);
                return "interview";
            }

            // 验证模型有效性
            if (!availableModels.contains(model)) {
                logger.warn("无效模型: {}, 自动切换为默认模型: {}", model, defaultModel);
                model = defaultModel;
            }

            // 获取选中的AI服务并执行分析
            AIService aiService = getAIServiceByModel(model);
            String analysisResult = aiService.analyzeResume(parsedText);

            // 创建并保存面试结果记录
            InterviewResult interviewResult = new InterviewResult();
            interviewResult.setUser(user);
            interviewResult.setResumeText(parsedText);
            interviewResult.setAnalysis(analysisResult);
            interviewResult.setConversationActive(true);
            interviewResult.setSelectedModel(model); // 记录选中的模型
            interviewResult = interviewResultRepository.save(interviewResult);

            logger.info("简历分析完成，结果ID: {}", interviewResult.getId());
            return "redirect:/interview/result/" + interviewResult.getId();

        } catch (Exception e) {
            logger.error("简历分析过程发生错误", e);
            modelAttr.addAttribute("error", "分析失败: " + e.getMessage());
            modelAttr.addAttribute("models", availableModels);
            modelAttr.addAttribute("defaultModel", defaultModel);
            return "interview";
        }
    }

    /**
     * 显示分析结果页面 - 包含对话功能和模型切换
     */
    @GetMapping("/result/{id}")
    public String viewResult(@PathVariable Long id, Authentication authentication, Model model) {
        try {
            User user = userService.findByUsername(authentication.getName());
            InterviewResult interviewResult = interviewResultRepository.findById(id)
                    .orElseThrow(() -> new RuntimeException("面试记录不存在（ID: " + id + "）"));

            // 验证访问权限
            if (!interviewResult.getUser().getId().equals(user.getId())) {
                logger.warn("用户 {} 尝试访问未授权的面试记录 {}", user.getUsername(), id);
                throw new RuntimeException("无权访问此面试记录");
            }

            // 传递数据到前端页面
            model.addAttribute("analysis", interviewResult.getAnalysis());
            model.addAttribute("resumeText", interviewResult.getResumeText());
            model.addAttribute("interviewId", interviewResult.getId());
            model.addAttribute("conversationHistory", interviewResult.getConversationHistory());
            model.addAttribute("conversationActive", interviewResult.isConversationActive());
            model.addAttribute("selectedModel", interviewResult.getSelectedModel());
            model.addAttribute("models", availableModels);

            return "result";
        } catch (Exception e) {
            logger.error("加载分析结果失败", e);
            model.addAttribute("error", "加载失败: " + e.getMessage());
            return "redirect:/dashboard";
        }
    }

    /**
     * 处理对话请求 - 支持在对话中切换模型
     */
    @PostMapping("/conversation")
    @ResponseBody
    public Map<String, Object> continueConversation(@RequestBody ConversationRequest request,
                                                    Authentication authentication) {
        Map<String, Object> response = new HashMap<>();
        logger.info("收到对话请求，面试ID: {}, 模型: {}", request.getInterviewId(), request.getModel());

        try {
            // 验证用户和面试记录
            User user = userService.findByUsername(authentication.getName());
            InterviewResult interviewResult = interviewResultRepository.findById(request.getInterviewId())
                    .orElseThrow(() -> new RuntimeException("面试记录不存在"));

            // 权限校验
            if (!interviewResult.getUser().getId().equals(user.getId())) {
                throw new RuntimeException("无权访问此面试记录");
            }

            // 确定使用的模型（请求模型优先，否则使用记录中的模型）
            String model = determineModel(request.getModel(), interviewResult.getSelectedModel());
            AIService aiService = getAIServiceByModel(model);

            // 处理对话逻辑
            interviewResult.addConversationMessage("我", request.getMessage());
            String aiResponse = aiService.continueConversation(
                    interviewResult.getResumeText(),
                    interviewResult.getConversationHistory(),
                    request.getMessage()
            );

            // 更新对话历史和模型选择
            interviewResult.addConversationMessage(aiService.getModelName() + "面试辅助", aiResponse);
            interviewResult.setSelectedModel(model);
            interviewResultRepository.save(interviewResult);

            // 构建成功响应
            response.put("success", true);
            response.put("message", aiResponse);
            response.put("model", model);

        } catch (Exception e) {
            logger.error("对话处理失败", e);
            response.put("success", false);
            response.put("message", "对话失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 查看用户的面试历史记录
     */
    @GetMapping("/history")
    public String interviewHistory(Authentication authentication, Model model) {
        try {
            User user = userService.findByUsername(authentication.getName());
            List<InterviewResult> history = interviewResultRepository.findByUserOrderByCreatedAtDesc(user);
            model.addAttribute("history", history);
            return "interview-history";
        } catch (Exception e) {
            logger.error("加载面试历史失败", e);
            model.addAttribute("error", "加载历史记录失败: " + e.getMessage());
            return "redirect:/dashboard";
        }
    }

    /**
     * 测试AI模型API连接
     */
    @GetMapping("/test-api")
    @ResponseBody
    public Map<String, Object> testAPI(@RequestParam(value = "model", defaultValue = "${ai.default.model}") String model) {
        Map<String, Object> result = new HashMap<>();
        try {
            AIService aiService = getAIServiceByModel(model);
            String testResponse = aiService.analyzeResume("测试简历内容：张三，Java开发工程师，3年工作经验");

            result.put("success", true);
            result.put("model", model);
            result.put("message", testResponse);
        } catch (Exception e) {
            result.put("success", false);
            result.put("model", model);
            result.put("message", "测试失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 解析简历内容（文件或文本）
     */
    private String parseResumeContent(MultipartFile file, String resumeText) {
        try {
            if (file != null && !file.isEmpty()) {
                logger.info("解析简历文件: {}", file.getOriginalFilename());
                return resumeParserService.parseResume(file);
            } else if (resumeText != null && !resumeText.trim().isEmpty()) {
                logger.info("使用输入的简历文本，长度: {}", resumeText.length());
                return resumeText.trim();
            }
            return null;
        } catch (Exception e) {
            logger.error("解析简历内容失败", e);
            throw new RuntimeException("解析简历失败: " + e.getMessage());
        }
    }

    /**
     * 确定使用的模型（优先级：请求模型 > 记录模型 > 默认模型）
     */
    private String determineModel(String requestModel, String recordModel) {
        if (requestModel != null && availableModels.contains(requestModel)) {
            return requestModel;
        }
        if (recordModel != null && availableModels.contains(recordModel)) {
            return recordModel;
        }
        return defaultModel;
    }

    /**
     * 根据模型名称获取对应的AI服务实例
     */
    private AIService getAIServiceByModel(String modelName) {
        switch (modelName.toLowerCase()) {
            case "doubao":
                return doubaoService;
            case "tongyi":
                return tongyiService;
            case "deepseek":
            default:
                return deepSeekService;
        }
    }
}
